package com.qire.manhua.dal.service;

import android.app.Activity;

import com.qire.antsbinder.dal.DataService;
import com.qire.antsbinder.dal.annotation.StrategyAnnotation;
import com.qire.antsrouter.lifecycleHandler.ActivityManageHandler;
import com.qire.common.basic.ObjectUtil;
import com.qire.common.basic.StringUtil;
import com.qire.common.constant.Url;
import com.qire.common.dal.WarehouseFactory;
import com.qire.common.utils.Logger;
import com.qire.common.utils.ToastHelper;
import com.qire.manhua.dal.ITradingDataDAL;
import com.qire.manhua.dal.IUserDataDAL;
import com.qire.manhua.model.enumeration.PaymentMethod;
import com.qire.manhua.model.viewModel.impl.BuyMembershipDialogViewModel;
import com.qire.manhua.model.viewModel.impl.BuyMembershipDialogViewModel.MembersPackageItemViewModel;
import com.qire.manhua.model.vo.MembersPackageVO;
import com.qire.manhua.model.vo.TradingOrderVO;
import com.qire.manhua.model.vo.TradingVerifyResponseVO;
import com.qire.manhua.model.vo.UserDetailVO;
import com.qire.other.thirdPlatform.AliPayPlatform;
import com.qire.other.thirdPlatform.WeChatPlatform;

public class BuyMembershipDialogService extends DataService {

    private final ITradingDataDAL tradingDataDAL = WarehouseFactory.create(this, ITradingDataDAL.class);
    private final IUserDataDAL userDataDAL = WarehouseFactory.create(this, IUserDataDAL.class);

    private final BuyMembershipDialogViewModel viewModel;

    public BuyMembershipDialogService(BuyMembershipDialogViewModel viewModel) {
        this.viewModel = viewModel;
    }

    /**
     * 加载会员充值套餐数据
     */
    public void loadPageData() {
        tradingDataDAL.fetchMembersPackage();
    }
    @StrategyAnnotation(event = Url.MembersPackage)
    public void fetchMembersPackageCallback(MembersPackageVO dataVO, boolean isCache) {
        if(ObjectUtil.isNull(dataVO) && ObjectUtil.isNull(dataVO.wares)) {
            return;
        }
        viewModel.clearMembersPackageList();
        for(MembersPackageVO.PackageInfoVO infoVO : dataVO.wares) {
            String describe      = infoVO.day + "天会员";
            String buyPrice      = String.valueOf(infoVO.fee);
            String originalPrice = "原价:" + infoVO._fee + "元";
            int beanReward = infoVO.bean * 100;
            String cornerLabel   = String.format("%.2f元/天", infoVO.pd);

            viewModel.addMembersPackageItem(describe, buyPrice, originalPrice, beanReward, cornerLabel);
        }
        viewModel.refreshMembersPackageAdapter();
        // 默认选中第一个
        viewModel.checkDefault();
    }

    /**
     * 创建会员套餐订单
     * @param selectPackageItem 选中会员套餐选项
     * @param paymentMethod 支付方式
     * @param payActivity 发起支付页面名
     */
    public void buyBuyMembership(MembersPackageItemViewModel selectPackageItem, PaymentMethod paymentMethod, String payActivity) {
        switch (paymentMethod) {
            case WeChatPay:
                tradingDataDAL.createWeChatOrder(selectPackageItem.buyPrice, 2, 2, 0, payActivity);
                return;
            case AliPay:
                tradingDataDAL.createAliPayOrder(selectPackageItem.buyPrice, 2, 2, 0, payActivity);
                return;
        }
    }
    @StrategyAnnotation(event = Url.WeChatPlaceOrder)
    public void createWeChatOrderCallback(TradingOrderVO orderVO, boolean isCache) {
        // 微信支付
        if(ObjectUtil.isNull(orderVO) || StringUtil.isEmpty(orderVO.ok)) {
            ToastHelper.showToast("创建订单失败");
            return;
        }

        TradingOrderVO.PayParamVO payParamVO = orderVO.payParam;
        if(ObjectUtil.isNull(payParamVO)) {
            ToastHelper.showToast("创建订单失败 payParam 为空");
            return;
        }
        Logger.d(payParamVO.toString());

        WeChatPlatform.PayParam payParam = new WeChatPlatform.PayParam(payParamVO.appId, payParamVO.partnerId, payParamVO.prepayId,
                payParamVO.nonceStr, payParamVO.timeStamp, payParamVO.sign, orderVO.outTradeNo);

        WeChatPlatform.WeChat.goPay(payParam, null,(msg, payCode, resultInfo) -> {
            String outTradeNo = (String) resultInfo;
            switch (payCode) {
                case WeChatPlatform.PAY_SUCCESS : {
                    tradingSyncVerify(PaymentMethod.WeChatPay, outTradeNo, "");
                    break;
                }
//                case WeChatPlatform.PAY_ERROR : {
//                    break;
//                }
//                case WeChatPlatform.PAY_CANCEL : {
//                    break;
//                }
            }
        });
    }
    @StrategyAnnotation(event = Url.AliPayPlaceOrder)
    public void createAliPayOrderCallback(TradingOrderVO orderVO, boolean isCache) {
        // 支付宝支付
        if(ObjectUtil.isNull(orderVO) || StringUtil.isEmpty(orderVO.ok)) {
            ToastHelper.showToast("创建订单失败");
            return;
        }


        if(StringUtil.isEmpty(orderVO.strJson)) {
            ToastHelper.showToast("创建订单失败 strJson");
            return;
        }

        Logger.d(orderVO.strJson);

        String outTradeNo = orderVO.outTradeNo;
        Activity activity = ActivityManageHandler.HANDLER.currentActivity();
        AliPayPlatform.AliPay.goPay(orderVO.strJson, activity, (msg, payCode, resultInfo) -> {
            switch (payCode) {
                case AliPayPlatform.PAY_SUCCESS : {
                    ToastHelper.showToast("支付成功");
                    tradingSyncVerify(PaymentMethod.AliPay, outTradeNo, (String) resultInfo);
                    break;
                }
                case AliPayPlatform.PAY_ERROR : {
                    ToastHelper.showToast("支付失败");
                    break;
                }
                case AliPayPlatform.PAY_CANCEL : {
                    ToastHelper.showToast("支付取消");
                    break;
                }
            }
        });
    }

    /**
     * 支付结束后同步交易结果校验
     * @param paymentMethod 交易类型
     */
    public void tradingSyncVerify(PaymentMethod paymentMethod, String outTradeNo, String aliPayResult) {
        switch (paymentMethod) {
            case WeChatPay:
                tradingDataDAL.tradingWeChatVerify(outTradeNo);
                return;
            case AliPay:
                tradingDataDAL.tradingAliPayVerify(outTradeNo, aliPayResult);
                return;
        }
    }
    @StrategyAnnotation(event = {Url.WeChatTradeVerify, Url.AliPayTradeVerify})
    public void tradeVerifyResponse(TradingVerifyResponseVO responseVO, boolean isCache) {
        refreshUserDetailData();

        //因为后台不一定及时收到第三方支付的回调，所以这个提示不一定准确
//        if(responseVO.payState == 0){
//            ToastHelper.showToast("订单未支付");
//            return;
//        }

        if(responseVO.activityState == 0) {
            // 没给活动地址
            viewModel.showBuyResult();
        } else {
            // 给了活动地址
            viewModel.showSpecialEvent(responseVO.webImgUrl, responseVO.webPageUrl);
        }
    }

    /**
     * 同步刷新用户资料，更新余额
     */
    private void refreshUserDetailData() {
        userDataDAL.refreshUserDetailData();
    }
    @StrategyAnnotation(event = Url.myIndex)
    public void requestMyIndexDataCallback(UserDetailVO dataVO, boolean isCache) {
        if(isCache || dataVO == null) return;
        dataVO.updateUserEntity();
    }

}
